export default class CP {
    //状态声明
    static PENDING = 'pending'
    static FULFILLED = 'fulfilled'
    static REJECTED = 'rejected'

    constructor(executor) {
        this.status = CP.PENDING
        this.value = null
        this.callback = []
        try {
            executor(this.resolve.bind(this), this.reject.bind(this))
        } catch (error) {
            this.reject(error)
        }
    }

    //活干好的，让人开心的事情
    resolve(value) {
        this.value = value
        this.status = CP.FULFILLED
        setTimeout(() => {
            this.callback.map(callback => callback.onResolve(value))
        })
    }

    // 没干好，伤心
    reject(reason) {
        this.value = reason
        this.status = CP.REJECTED
        setTimeout(() => {
            this.callback.map(callback => callback.onReject(reason))
        })
    }
    //任务结果进行处理
    then(onResolve, onReject) {
        //验证校验
        if (typeof onResolve !== 'function') {
            onResolve = value => value
        }
        if (typeof onReject !== 'function') {
            onReject = value => value
        }

        //为了支持链式调用
        return new CP((resolve, reject) => {
            // 要把上一个Promise的then函数保留起来
            this.callback.push({
                onResolve: value => {
                    //上一个任务的then的成功回调
                    const result = onResolve(value)
                    if (result instanceof CP) {
                        // alert('返回了PROMISE对象')
                        //如果then回调函数返回的是Promise,我们要获取该promise执行结果
                        //返回给本次的Promise 的 resolve 函
                        result.then(value => {
                            // console.log(value)
                            resolve(value)
                        })
                        // resolve(result)
                    } else {
                        //本次promise的成功回调
                        resolve(result)
                    }
                },
                onReject: reason => {
                    const result = onReject(reason)
                    resolve(result)
                },
            })
        })
    }

    static all(promises) {
        let values = []
        return new CP((resolve, reject) => {
            promises.forEach(promise => {
                promise.then(
                    value => {
                        values.push(value)
                        if (values.length === promises.length) {
                            resolve(values)
                        }
                    },
                    reason => {
                        reject(reason)
                    }
                )
            })
        })
    }
}

// framework inertia
